package application;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class ServerHandler implements IoHandler {

	private static Logger log = Logger.getLogger(ServerHandler.class);
	private static ServerHandler serverHandler = null;

	public static ServerHandler getInstances() {
		if (null == serverHandler) {
			serverHandler = new ServerHandler();
		}
		return serverHandler;
	}

	private ServerHandler() {}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		log.info("连接建立:" + session.getRemoteAddress());
	}

	@Override
	public void sessionClosed(IoSession session) {

	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		if (message instanceof String) {
//			System.out.println(message);
			System.out.println(((String) message).length());
			session.write("服务器收到消息：" + message + message);
		}
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable arg1)
			throws Exception {
		log.error("ip:" + session.getRemoteAddress() + "," + arg1);
	}

	@Override
	public void messageSent(IoSession arg0, Object arg1) throws Exception {

	}

	@Override
	public void sessionCreated(IoSession arg0) throws Exception {

	}

	public void sessionIdle(IoSession session, IdleStatus idleStatus) throws Exception {
		session.close(true);
	}

}
